package model;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class leaderboard {
	ArrayList<record> records = new ArrayList<record>();
	
	public leaderboard() {
		importRecords();
	}
	
	private void importRecords() {
		
	    FileReader reader;
	    
		try {
			reader = new FileReader("leaderboard.txt");
		    Scanner in = new Scanner(reader);

		    while (in.hasNextLine()) {
		    	String line = in.nextLine();
		    	String temp[];
		    	temp = line.split(",");
		    	records.add(new record(temp[0], Integer.parseInt(temp[1])));
		    	//add scores to arraylist
		    }		
		    in.close();		    
		} 
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public  ArrayList<record> getRecords() {
		return records;
	}
	
	//return -1 if score not good enough
	public int checkHighScore(int s) {
		int index = -1;
		
		for (int i = 0; i < records.size(); i++) {
			if (s > records.get(i).getScore()) {
				index = i;
				break;
			}
		}
		return index;
	}
	
	public void addRecord(String n, int s, int index) {
		//add new score, remove last score
		records.add(index, new record(n, s));
		records.remove(records.size()-1);
		writeRecords();	
	}
	
	private void writeRecords() {
		
	    FileWriter writer;
	   
			try {
				writer = new FileWriter("leaderboard.txt");
				
				for (int i = 0; i < records.size(); i++) {
			    	writer.write(records.get(i).getName() + "," + records.get(i).getScore() + "\r\n");
			    }	
			    writer.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		    		    
	
	}
	
	/** TEST METHODS */
	
	private void testPrintInfo() {
		for (int i = 0; i <records.size() ; i++) 
			System.out.println("index: " + 0 + ", Name: " + records.get(i).getName() + ", Score: " + records.get(i).getScore());		
	}

}
